package codeRandomThoughts.Test279完全平方数;

import java.util.Arrays;

public class Solution {
    public int numSquares(int n) {
        int max = Integer.MAX_VALUE;
        //dp[j]:编号为0~i的完全平方数任选凑成j的最少数量为dp[j]
        int[] dp = new int[n + 1];
        Arrays.fill(dp, max);

        //1<=n<=10000
        //题目中规定的完全平方数从1开始 所以dp[0] = 0
        dp[0] = 0;

        //如果完全平方数大于n 没有必要遍历
        for (int i = 0; i * i <= n; i++) {
            int ps = i * i;
            for (int j = ps; j <= n; j++) {
                int num = dp[j - ps];
                if (num != max) {
                    dp[j] = Math.min(num + 1, dp[j]);
                }
            }
        }

        return dp[n] == max ? -1 : dp[n];
    }
}
